package com.pocketsweet.ui.uilib.adapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVPush;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.model.MLUserLike;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.TopicArticle;
import com.pocketsweet.ui.fragments.NewOnlineFragment;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.SlideView;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

import org.json.JSONException;
import org.json.JSONObject;

import c.t.m.g.t;

/**
 * @author Kam
 */
public class OnLineTestLoverAdapter extends BaseListAdapter<MLUser> {
    private List<MLUser> user;
    private int i = 0;
    private ArrayList<String> userLikeID = new ArrayList<String>();
    private Context context;

    final int TYPE_CALL = 0;
    final int TYPE_USER = 1;

    public OnLineTestLoverAdapter(Context ctx) {
        super(ctx);
        this.context = ctx;
    }

    public OnLineTestLoverAdapter(Context ctx, List<MLUser> datas) {
        super(ctx, datas);
        this.context = ctx;
    }

    //
    // @Override
    // public int getItemViewType(int p) {
    // if (p == 0)
    // return TYPE_CALL;
    // else
    // return TYPE_USER;
    //
    // }

    @Override
    public int getViewTypeCount() {
        return 1;
        // return 2;
    }

    @Override
    public int getCount() {
        if (datas != null && datas.size() > 0) {
            // return datas.size() + 1;
            return datas.size();
        } else {
            return 0;
        }
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);

        // if (type == TYPE_CALL) {
        // convertView = inflater.inflate(R.layout.view_test_lover_banner,
        // parent, false);
        // CallHolder callHolder = new CallHolder(convertView);
        // convertView.setTag(callHolder);
        // return convertView;
        // } else {
        ViewHolder viewHolder = null;
        SlideView slideView = (SlideView) convertView;
        if (slideView == null) {
            View itemView = inflater.inflate(R.layout.item_online_container,
                    null);
            slideView = new SlideView(MLApplication.getContext());
            slideView.setContentView(itemView);
            viewHolder = new ViewHolder(slideView);
            slideView.setOnSlideListener(NewOnlineFragment.slideLister);
            slideView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // datas.get(position - 1).slide = slideView;
        datas.get(position).slide = slideView;
        // viewHolder.refreshView(datas.get(position - 1), position);
        viewHolder.refreshView(datas.get(position), position);
        return slideView;
        // }

    }

    //
    // public class CallHolder {
    // private View parent;
    //
    // public CallHolder(View parent) {
    // this.parent = parent;
    // }
    // }

    public class ViewHolder implements View.OnClickListener {
        ImageView imgAvatar;
        TextView tvuserName;
        TextView tvUserAge;
        // TextView tvFrom;
        // TextView tvStar;
        // ImageView tvHasMoney;
        // TextView tvHasVoice;
        TextView tvLike;
        TextView tvUserMood;
        TextView tvType;
        TextView tvIsReCommanded;
        TextView tvTimeDiff;
        MLUser item;
        RelativeLayout holder;
        private View parent;
        private String articleId;
        private int likeCount = 0;
        public LoadingDailog loading;

        public ViewHolder(View parent) {
            this.parent = parent;
            initView(parent);
        }

        public void initView(View parent) {
            imgAvatar = (ImageView) parent.findViewById(R.id.imgAvatar);
            // tvHasMoney = (ImageView) parent.findViewById(R.id.tvHasMoney);
            tvuserName = (TextView) parent.findViewById(R.id.tvuserName);
            tvUserAge = (TextView) parent.findViewById(R.id.tvOnlineUserAge);
            // tvFrom = (TextView) parent.findViewById(R.id.tvFrom);
            // tvStar = (TextView) parent.findViewById(R.id.tvStar);
            // tvHasVoice = (TextView) parent.findViewById(R.id.tvHasVoice);
            tvLike = (TextView) parent.findViewById(R.id.tvLikeCount);
            tvUserMood = (TextView) parent.findViewById(R.id.tvUserMood);
            tvIsReCommanded = (TextView) parent
                    .findViewById(R.id.tvIsReCommanded);
            tvTimeDiff = (TextView) parent.findViewById(R.id.tvTimeDiff);
            tvType = (TextView) parent.findViewById(R.id.tvType);
            holder = (RelativeLayout) parent.findViewById(R.id.holder);
            loading = ToolKits.createLoadingDialog(ctx, "提交中..");
            loading.setText("加载中");
            // tvuserName.setEms(10);
            // tvuserName.setEllipsize(TruncateAt.END);
            // tvuserName.setSingleLine(true);

        }

        public void refreshView(MLUser item, int i) {
            this.item = item;
            String location = null;
            String suburl = item.getSubAvatar();
            String avatar = (suburl != null && !suburl.equals("") && !suburl
                    .equals("null")) ? item.getSubAvatar() : item
                    .getAvatarUrl();

            if (avatar != null && !avatar.equals("")) {
                UserService.displaySquare(avatar, imgAvatar);
                imgAvatar.setTag(avatar);
            } else {
                imgAvatar.setImageResource(R.drawable.default_user_avatar);
            }
            // 设置姓名
            tvuserName.setText(item.getNickname());
            if (!StringUtils.isEmpty((item.getBelong()))) {
                tvType.setText(item.getBelong());
                tvType.setVisibility(View.VISIBLE);
            } else {
                tvType.setVisibility(View.GONE);
            }
            // 判断是否推荐的人
            if (item.getArticle() != null) {
                item.slide.isScroll = true;
            } else {
                item.slide.isScroll = false;
                // mlUser.slide.setOnSlideListener(null);
            }
            // 设置点赞次数,点赞红心
            likeCount = item.getLikeCount();
            tvLike.setText(String.valueOf(likeCount));
            checkUserLike(item); // 检查是否喜欢过此人
            tvLike.setOnClickListener(this);
            // 设置年龄
            if (!StringUtils.isEmpty(String.valueOf(item.getAgeNum()))) {
                tvUserAge.setText(String.valueOf(item.getAgeNum()));
                tvUserAge.setVisibility(View.VISIBLE);
            } else {
                tvUserAge.setVisibility(View.GONE);
            }
            // 设置性别颜色
            if (item.getGender() == 1) {
                tvUserAge
                        .setBackgroundResource(R.drawable.shape_rectangle_bule);
            } else if (item.getGender() == 2) {
                // 设置颜色
                tvUserAge.setBackgroundResource(R.drawable.shape_rectangle_red);

            }
            // 设置声音
            // if (mlUser.getIsHasVoice()) {
            // tvHasVoice.setVisibility(View.VISIBLE);
            // } else {
            // tvHasVoice.setVisibility(View.GONE);
            // }
            // 设置星座
            // if (!StringUtils.isEmpty(mlUser.getConstellation())) {
            // tvStar.setText(mlUser.getConstellation());
            // tvStar.setVisibility(View.VISIBLE);
            // } else {
            // tvStar.setVisibility(View.GONE);
            // }
            // 设置地理位置
            location = item.getLocationCity();
            if (StringUtils.isEmpty(location)) {
                location = item.getLocationProvince();
            }
            // if (!StringUtils.isEmpty(location)) {
            // tvFrom.setText(location);
            // tvFrom.setVisibility(View.VISIBLE);
            // } else {
            // tvFrom.setVisibility(View.GONE);
            // }
            // 设置描述
            tvUserMood.setText(item.getIntro());
            if (item.getArticle() != null) {
                articleId = item.getArticle().getObjectId();
            }
            holder.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // 跳到文章
                    loading.show();
                    AVQuery<MLArticle> query = new AVQuery<MLArticle>(
                            "MLArticle");
                    query.getInBackground(articleId,
                            new GetCallback<MLArticle>() {

                                @Override
                                public void done(MLArticle arg0, AVException e) {
                                    loading.dismiss();
                                    if (e == null) {
                                        if (arg0 != null) {
                                            Intent intent = new Intent(ctx,
                                                    TopicArticle.class);
                                            intent.putExtra("articleId",
                                                    articleId);
                                            ctx.startActivity(intent);
                                        } else {
                                            ToolKits.toast(ctx, "暂无编辑推荐文章");
                                        }
                                    } else {
                                        ToolKits.toast(ctx, "暂无编辑推荐文章");

                                    }
                                }
                            });
                }
            });
            tvIsReCommanded.setVisibility(View.GONE);
            tvTimeDiff.setText(ToolKits.getTimeDiff(item.getLastLoginTime()));// 几分钟之前

        }

        /*
         * 查询该对象被点赞的次数并赋值以及保存
         */
        public void checkUserLike(final MLUser user) {
            // MLContext.deleteAll();
            if (MLContext.getUserLikeSize("userSize") == -1) { // 当sharepreference的数量为空时从网络获取
                final AVQuery<AVObject> query = new AVQuery<AVObject>(
                        "MLUserLike");
                query.whereEqualTo("likeUser", user);
                query.whereEqualTo("user", UserService.getCurrentUser());
                query.findInBackground(new FindCallback<AVObject>() {
                    @Override
                    public void done(List<AVObject> list, AVException arg1) {
                        if (arg1 == null) {
                            if (list.size() > 0) {
                                tvLike.setText(String.valueOf(list.size()));
                                for (AVObject tempUser : list) {
                                    MLUserLike tempMLLike = (MLUserLike) tempUser;
                                    if (tempMLLike.getLikeUser().equals(user)) {
                                        setLikeSb();
                                        MLContext.saveUserLikeID(user
                                                .getObjectId());
                                        MLContext.saveLike(
                                                MLContext.LIKE_TYPE_USER, user
                                                        .getObjectId()
                                                        .toString());
                                        break;
                                    }
                                }
                            } else {
                                MLContext.getInstance().setUserLikeSizeZero();
                            }
                        } else {
                            // Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());

                        }

                    }
                });
            } else { // 当sharepreference有点赞纪录时从本地获取
                // Log.e("=====", "==got==本地有点赞纪录");
                if (MLContext.getUserLikeID(user.getObjectId()) != 0) {
                    setLikeSb();
                    // Log.e("=====", "==got==已喜欢某人");

                } else {
                    setCancleLikeSb(); // 设置红心取消
                    // Log.e("=====", "==got==不喜欢某人");

                }

            }

        }

        public void update(final MLUser user) {
            tvLike.setText(String.valueOf(user.getLikeCount()));
            if (MLContext.getUserLikeID(user.getObjectId()) != 0) {
                setLikeSb();
            } else {
                setCancleLikeSb(); // 设置红心取消
            }
        }

        /*
         * 喜欢该对象，并保存该数据到leanCloud
         */
        private void likeSb(final MLUser user) {
            tvLike.setClickable(false); // 正在点赞，不准重复点击
            Map<String, Object> params = new HashMap<String, Object>();
            final String userId = user.getObjectId();
            params.put("userId", userId);
            AVCloud.callFunctionInBackground("likeUser", params,
                    new FunctionCallback<Object>() {

                        @Override
                        public void done(Object arg0, AVException e) {
                            if (e == null) {
                                Map<String, Object> params = new HashMap<String, Object>();
                                MLUser curUser = UserService.getCurrentUser();
                                params.put("touserId", userId);
                                params.put("fromuserId", curUser.getObjectId());
                                params.put("nick", curUser.getNickname());
                                AVCloud.callFunctionInBackground(
                                        "sendNewLikerMsg", params,
                                        new FunctionCallback<Object>() {

                                            @Override
                                            public void done(Object arg0,
                                                             AVException e) {
                                                if (e == null) {
                                                    AVQuery pushQuery = AVInstallation.getQuery();
                                                    pushQuery.whereEqualTo("channels", userId);
                                                    AVPush push = new AVPush();
                                                    push.setQuery(pushQuery);
                                                    JSONObject data;
                                                    try {
                                                        data = new JSONObject(
                                                                "{\"alert\": \""
                                                                        + UserService
                                                                        .getCurrentUser()
                                                                        .getNickname()
                                                                        + "喜欢了你，快去翻翻看\", \"sound\": \"default\"}");
                                                        push.setData(data);

                                                        push.sendInBackground();

                                                    } catch (JSONException e1) {
                                                        // TODO Auto-generated catch block
                                                        e1.printStackTrace();
                                                    }
                                                    likeCount++;
                                                    item.setLikeCount(likeCount);
                                                    setLikeSb(); // 喜欢该对象，设置红心
                                                    tvLike.setText(String
                                                            .valueOf(likeCount)); // 点赞数量加一
                                                    // ToolKits.toast(ctx,
                                                    // "点赞成功");
                                                    MLContext
                                                            .saveUserLikeID(user
                                                                    .getObjectId());
                                                    MLContext
                                                            .saveLike(
                                                                    MLContext.LIKE_TYPE_USER,
                                                                    user.getObjectId()
                                                                            .toString());

                                                    tvLike.setClickable(true); // 可点击了
                                                } else {
                                                    ToolKits.toast(ctx,
                                                            "喜欢失败，请检查网络");
                                                    tvLike.setClickable(true); // 可点击了
                                                }

                                            }

                                        });
                            } else {
                                ToolKits.toast(ctx, "喜欢失败，请检查网络");
                                tvLike.setClickable(true); // 可点击了
                            }
                        }

                    });
        }

        /*
         * 不喜欢该对象，并保存该数据到leanCloud
         */
        private void unLikeSb(final MLUser user) {
            tvLike.setClickable(false); // 正在点赞，不准重复点击
            likeCount--;
            Map<String, Object> params = new HashMap<String, Object>();
            final String userId = user.getObjectId();
            params.put("userId", userId);
            AVCloud.callFunctionInBackground("disLikeUser", params,
                    new FunctionCallback<Object>() {

                        @Override
                        public void done(Object arg0, AVException e) {
                            if (e == null) {
                                item.setLikeCount(likeCount);
                                tvLike.setText(String.valueOf(likeCount)); // 点赞数量减一
                                setCancleLikeSb(); // 不喜欢该对象，取消红心
                                MLContext.deleteUserLikeID(user.getObjectId());
                                MLContext.deleteLike(MLContext.LIKE_TYPE_USER,
                                        user.getObjectId().toString());
                                Intent intent = new Intent();
                                intent.setAction(Main.ACTION_LIKE_POEPLE);
                                ctx.sendBroadcast(intent);
                                tvLike.setClickable(true); // 可点击了
                            } else {
                                ToolKits.toast(ctx, "取消喜欢失败，请检查网络");
                                tvLike.setClickable(true); // 可点击了
                            }

                        }

                    });

        }

        /*
         * 取消喜欢该对象，设置红心取消
         */
        private void setCancleLikeSb() {
            // Drawable drawble_right_unpress = ctx.getResources().getDrawable(
            // R.drawable.btn_like_unpless); // 取消点赞红心
            // drawble_right_unpress.setBounds(0, 0,
            // drawble_right_unpress.getMinimumWidth(),
            // drawble_right_unpress.getMinimumHeight());
            // tvLike.setCompoundDrawables(null, null, drawble_right_unpress,
            // null);
            tvLike.setBackgroundResource(R.drawable.shape_rectangle_cancle_love);
        }

        /*
         * 喜欢该对象，设置红心
         */
        private void setLikeSb() {
            // Drawable drawble_right_press = ctx.getResources().getDrawable(
            // R.drawable.btn_like_pless); // 取消点赞红心
            // drawble_right_press.setBounds(0, 0,
            // drawble_right_press.getMinimumWidth(),
            // drawble_right_press.getMinimumHeight());
            // tvLike.setCompoundDrawables(null, null, drawble_right_press,
            // null);
            tvLike.setBackgroundResource(R.drawable.shape_rectangle_love);
        }

        /*
         * 喜欢该对象，在MLUserLike表上添加或者删除纪录
         */
        private void setMLUserLike(final MLUser user) {
            final AVQuery<AVObject> query = new AVQuery<AVObject>("MLUserLike");
            query.whereEqualTo("likeUser", user);
            query.whereEqualTo("user", UserService.getCurrentUser());
            query.findInBackground(new FindCallback<AVObject>() {
                public void done(List<AVObject> avObjects, AVException e) {
                    if (e == null) {
                        if (avObjects.size() <= 0) { // 当用户以前没有喜欢过，则喜欢该对象
                            // likeSb(user); // 喜欢该对象，并保存该数据到leanCloud
                            MLUserLike like = new MLUserLike();
                            MLUser currentUser = new MLUser();
                            currentUser.setObjectId(UserService.getCurrentUserId());
                            MLUser toUser = new MLUser();
                            toUser.setObjectId(user.getObjectId());
                            like.setUser(currentUser);
                            like.setLikeUser(toUser);
                            like.saveInBackground(new SaveCallback() {

                                @Override
                                public void done(AVException arg0) {
                                    if (arg0 == null) {
                                        likeSb(user);
                                    } else {
                                        tvLike.setClickable(true);
                                    }

                                }
                            });
                        } else { // 当用户已经喜欢过，则取消喜欢
                            query.deleteAllInBackground(new DeleteCallback() {

                                @Override
                                public void done(AVException arg0) {
                                    if (arg0 == null) {
                                        //setCancleLikeSb(); // 设置红心取消
                                        unLikeSb(user);
                                    } else {
//                                         Log.e("删除失败",
//                                         "查询错误: "
//                                         + arg0.getMessage());
                                        tvLike.setClickable(true);
                                    }

                                }
                            });
                        }
                    } else {
//                         Log.e("失败", "查询错误: " + e.getMessage());
                        tvLike.setClickable(true);
                    }
                }
            });

        }

        @Override
        public void onClick(View v) {
            if (v.equals(parent)) {
                // TODO 查看用户资料
            } else if (v.equals(tvLike)) {
                final MLUser user = item;
//                if (MLContext.getUserLikeID(user.getObjectId()) != 0) { // 当用户已经被点赞过,则取消点赞
//                    unLikeSb(user); // 不喜欢该对象
//                } else { // 当用户没点赞过,则点赞
//                    likeSb(user); // 喜欢该对象，并保存该数据到leanCloud
//                }
                tvLike.setClickable(false); // 正在点赞，不准重复点击
                setMLUserLike(user); // 在MLLike表上添加或者删除纪录
                AVAnalytics.onEvent(ctx, "喜欢实习恋人");
            }
        }
    }
}
